package tech.yixiyun.framework.kuafu.db.datasource;

import tech.yixiyun.framework.kuafu.db.DbException;
import tech.yixiyun.framework.kuafu.domain.DomainContext;
import tech.yixiyun.framework.kuafu.domain.DomainDefinition;
import tech.yixiyun.framework.kuafu.kits.StringKit;
import tech.yixiyun.framework.kuafu.log.LOGGER;
import tech.yixiyun.framework.kuafu.shutdown.ShutdownRegistry;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 数据库连接池管理类
 */
public class DataSourceContext {

    private static final ConcurrentHashMap<String, DataSourceDefinition> dataSources = new ConcurrentHashMap<>();

    private static String mainSourceKey; //主数据源key

    public static String getMainSourceName() {
        return mainSourceKey;
    }

    /**
     * 根据Domain类上的注解，分析它是哪个数据源的
     * @param domainClass
     * @return
     */
    public static String getDomainSourceName(Class domainClass) {
        DomainDefinition domain = DomainContext.getDomainDefinition(domainClass);
        if (domain == null) {
            throw new RuntimeException(domainClass + "未注册为Domain");
        }
        String dataSource = domain.getDataSource();
        if (StringKit.isBlank(dataSource)) {
            return getMainSourceName();
        }
        return dataSource;
    }

    /**
     * 注册数据源
     * @param definition
     * @return
     */
    public static DataSourceDefinition register(DataSourceDefinition definition) {
        if (StringKit.isBlank(definition.getName()) ) {
            throw new DbException("数据源定义未配置name（为数据源起的名字），注册失败");
        }

        if (definition.getDataSource() == null) {
            throw new DbException("数据源定义未配置datasource，注册失败");
        }
        if (definition.getDbType() == null) {
            throw new DbException("数据源定义未配置数据库类型，注册失败");

        }

        if (dataSources.size() == 0) { //第一个默认就是主数据源
            mainSourceKey = definition.getName();
        } else if (definition.getIsMain()){
            mainSourceKey = definition.getName();
        }
        DataSourceDefinition temp = dataSources.putIfAbsent(definition.getName(), definition);
        if (temp != null) {
            throw new DbException("名为"+definition.getName()+"的DataSource已在DataSourceContext中注册，注册失败");
        }
        LOGGER.infoTitle("启动：注册name为"+definition.getName()+"的数据源");

        ShutdownRegistry.register(() -> {
            definition.close();
        });
        return definition;
    }



    /**
     * 根据数据源名字获取数据源
     * @param name
     * @return
     */
    public static DataSourceDefinition getDataSource(String name) {
        DataSourceDefinition definition = dataSources.get(name);
        if (definition == null) {
            throw new DbException("未注册名为" + name + "的数据源");
        }
        return definition;
    }

    /**
     * 获取主数据源
     * @return
     */
    public static DataSourceDefinition getMainDataSource() {
        if (mainSourceKey == null) {
            LOGGER.warn("未配置主数据源");
            return null;
        }

        return dataSources.get(mainSourceKey);
    }






}
